package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private VipServiceConfigFeignClient vipServiceConfigFeignClient;

    /**
     * 订单结算页
     * @param tradeVo
     * @param userId
     * @return
     */
    @Override
    public OrderInfoVo trade(TradeVo tradeVo, Long userId) {
        //创建对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //原始金额
        BigDecimal originalAmount = new BigDecimal("0.00");
        //减免金额
        BigDecimal derateAmount = new BigDecimal("0.00");
        //订单总金额
        BigDecimal orderAmount = new BigDecimal("0.00");
        //订单明细列表
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        //订单减免明细列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //订单结算页 专辑 声音 vip
        if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())){
            //专辑
            Long albumId = tradeVo.getItemId();
            //通过远程调用 获取用户是否购买过专辑
            Result<Boolean> paidAlbumResult = userInfoFeignClient.isPaidAlbum(albumId);
            Assert.notNull(paidAlbumResult, "专辑信息不存在");
            //购买过就直接返回
            if (paidAlbumResult.getData()){
                throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
            }
            //获取专辑信息
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            Assert.notNull(albumInfoResult, "专辑信息不存在");
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo, "专辑对象不存在");
            //原始金额
            originalAmount=albumInfo.getPrice();
            //查询用户信息 判断是否是vip
            Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
            Assert.notNull(userInfoVoResult, "用户信息不存在");
            UserInfoVo userInfoVo = userInfoVoResult.getData();
            Assert.notNull(userInfoVo, "用户对象不存在");
            if (userInfoVo.getIsVip()==0||(userInfoVo.getIsVip()==1&&userInfoVo.getVipExpireTime().before(new Date()))){
                //普通用户
                //有折扣 1000*(10-8)/10 减免金额
                if (albumInfo.getDiscount().compareTo(new BigDecimal("-1"))>0) {
                    derateAmount = originalAmount.multiply(new BigDecimal("10").subtract(albumInfo.getDiscount())).divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                }
            }else {
                //vip用户
                if (albumInfo.getVipDiscount().compareTo(new BigDecimal("-1"))>0) {
                    //有折扣 1000*(10-8)/10 减免金额
                    derateAmount = originalAmount.multiply(new BigDecimal("10").subtract(albumInfo.getVipDiscount())).divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                }
            }
            //订单总金额
            orderAmount=originalAmount.subtract(derateAmount);
            //订单明细列表
            //创建对象
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            //赋值
            orderDetailVo.setItemId(albumId);
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVoList.add(orderDetailVo);

            //订单减免明细列表
            if (derateAmount.compareTo(new BigDecimal("0.00"))>0){
                //创建对象
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                //赋值
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("专辑优惠券");
                orderDerateVoList.add(orderDerateVo);
            }
        }else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(tradeVo.getItemType())){
            //声音
        }else {
            //vip
            Long vipServiceConfigId  = tradeVo.getItemId();
            //通过远程调用 获取vip 服务配置信息
            Result<VipServiceConfig> vipServiceConfigResult = vipServiceConfigFeignClient.getVipServiceConfig(vipServiceConfigId);
            Assert.notNull(vipServiceConfigResult, "vip服务配置信息不存在");
            VipServiceConfig vipServiceConfig = vipServiceConfigResult.getData();
            Assert.notNull(vipServiceConfig, "vip服务配置对象不存在");
            //原始金额
            originalAmount=vipServiceConfig.getPrice();
            //订单总金额
            orderAmount=vipServiceConfig.getDiscountPrice();
            //减免金额
            derateAmount=originalAmount.subtract(orderAmount);
            //订单明细列表
            //创建对象
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            //赋值
            orderDetailVo.setItemId(vipServiceConfigId);
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemPrice(orderAmount);
            orderDetailVoList.add(orderDetailVo);
            //订单减免明细列表
            if (derateAmount.compareTo(new BigDecimal("0.00"))>0){
                //创建对象
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                //赋值
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("vip优惠券");
                orderDerateVoList.add(orderDerateVo);
            }
        }

        //赋值
        orderInfoVo.setTradeNo(UUID.randomUUID().toString().replaceAll("-",""));
        orderInfoVo.setPayWay("");
        orderInfoVo.setItemType(tradeVo.getItemType());
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        //时间戳
        long timestamp = SignHelper.getTimestamp();
        orderInfoVo.setTimestamp(timestamp);
        //签名 保证接口安全性
        Map map = JSON.parseObject(JSON.toJSONString(orderInfoVo), Map.class);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);
        return orderInfoVo;
    }
}
